from rest_framework import serializers
from rest_framework.fields import SerializerMethodField
from rest_framework.serializers import ModelSerializer

from community.models import Label, Article, Comment


# 标签序列化器
class LableSerializer(ModelSerializer):
    class Meta:
        model = Label
        fields = '__all__'



# 文章序列化器
class ArticleSerializer(ModelSerializer):
    user_name = serializers.CharField(source='user.username', read_only=True)
    user_avatar = serializers.CharField(source='user.userdetail.avatar', read_only=True)
    label_name = serializers.CharField(source='label.name', read_only=True)
    class Meta:
        model = Article
        exclude = ["is_delete"]
        extra_kwargs = {
            "page_view":{'read_only': True},
            "priority":{'read_only': True}
        }


# 评论序列化器
class CommentSerializer(ModelSerializer):
    user_name = serializers.CharField(source='user.username', read_only=True)
    user_avatar = serializers.CharField(source='user.userdetail.avatar', read_only=True)
    son_comment_count = SerializerMethodField(read_only=True)
    class Meta:
        model = Comment
        exclude = ["is_delete"]
    #
    def get_son_comment_count(self, comment):
        # 通过评论管理器 得到所有的子级评论个数
        return comment.parent_comment_set.count()

# 评论人之间信息展示序列化器
class SonCommentSerializer(ModelSerializer):
    user_name = serializers.CharField(source='user.username', read_only=True)
    user_avatar = serializers.CharField(source='user.userdetail.avatar', read_only=True)
    reply_username = serializers.CharField(source = 'reply_comment.user.username',read_only = True)
    class Meta:
        model = Comment
        exclude = ["is_delete"]

